<?php

namespace app\forms\position;

use yii\db\Exception;
use app\models\Position;
use yii\web\HttpException;
use app\helpers\ArrayHelper;
use app\validators\PositiveInteger;

/**
 * 岗位 编辑
 */
class UpdateForm extends BaseForm
{
    public $id;
    public $setDefault = 0;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['id', PositiveInteger::class],
            ['id', 'required', 'message' => 'ID不能为空'],
            ['id', 'exist', 'targetClass' => Position::class],

            ['setDefault', 'boolean'],
        ]);
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {

            $attr = $form->getAttributes();
            $attr = ArrayHelper::humpToUnderline($attr);
            unset($attr['item'], $attr['auth']);

            // 岗位
            $position = Position::findOne($form['id']);
            $position->setAttributes($attr);
            $position->save(false);

            // 权限
            $position->removeItem();
            $position->addItem($form->item, $form->auth, $form->data);

            // 设置默认权限
            if ($form->setDefault) {
                $position->removeDefaultItem();
                $position->addDefaultItem($form->item, $form->auth, $form->data);
            }

            // casbin 操作

        } catch (Exception $e) {
            $form->serverError();
        }

        $form->updateOk();
    }
}